package zut.edu.cn.concertticketmanagementsystem.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import zut.edu.cn.concertticketmanagementsystem.entity.Result;
import zut.edu.cn.concertticketmanagementsystem.entity.User;
import zut.edu.cn.concertticketmanagementsystem.service.UserService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * User: cyl
 * Date: 2019/6/23
 * Time: 11:43
 * Description: No Description
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 注册
     *
     * @param user 参数封装
     * @return Result
     */
    @RequestMapping(value = "/register")
    public String register(User user) {

        Result result = new Result();
        if(user.getUsername()==""||user.getPassword()=="")
            return "registererror";

        result = userService.register(user);

        if(result.getMsg().equals("注册成功")) {
            return "redirect:/login";
        }
        else
            return "registererror";

    }

    /**
     * 登录
     *
     * @param user 参数封装
     * @return Result
     */
    @PostMapping(value = "/login")
    public String login(User user, RedirectAttributes attr, HttpServletResponse response, HttpServletRequest request) {

        Result result = new Result();
        if(user.getUsername()==""||user.getPassword()=="")
            return "loginerror";

        result = userService.login(user);
        if (result.getMsg().equals("用户名或密码错误")) {

            return "loginerror";

        }
        else {
            Cookie cookie = new Cookie("username", user.getUsername());
            response.addCookie(cookie);
            attr.addAttribute("username",user.getUsername());
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            return "redirect:/lmh";
        }

    }

    @RequestMapping(value = "/quit")
    public String quit( RedirectAttributes attr, HttpServletResponse response, HttpServletRequest request) {

        HttpSession session = request.getSession();
        session.removeAttribute("user");
        return "redirect:/login";
    }


}
